<template>
  <el-table 
  :data="orders" 
  style="width: 100%" 
  empty-text="暂无相关订单"
  @row-click="handleRowClick"
  class="clickable-rows">
    <el-table-column label="商品信息" width="400">
      <template #default="{ row }">
        <div class="product-info">
          <el-image
            :src="row.product_image"
            class="product-image"
            fit="contain"
            :preview-src-list="[row.product_image]"
          />
          <div class="product-details">
            <div class="product-name">{{ row.product_name }}</div>
            <div class="product-price">¥{{ row.product_price.toFixed(2) }}</div>
          </div>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="数量" width="100">
      <template #default="{ row }">{{ row.quantity }}</template>
    </el-table-column>

    <el-table-column label="状态说明" width="200">
      <template #default="{ row }">
        <div v-if="row.order_payment_status === 0" class="status-container">
          <div class="status unpaid">待支付</div>
          <el-button
            type="danger"
            size="small"
            @click.stop="deleteOrder(row.order_id)"
            class="delete-btn"
          >删除</el-button>
          <el-button
            type="primary"
            size="small"
            @click.stop="handlePayment(row)"
            :loading="row.paying"
            style="margin-left: 10px"
          >支付</el-button>
        </div>
        <div v-else-if="row.order_delivery_status === 0" class="status pending">
          已支付，正在打包等待发货
        </div>
        <div v-else class="status delivered">
          已发货
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { defineProps } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

const handleRowClick = (row) => {
  router.push(`/order/${row.order_id}`);
};

const props = defineProps({
  orders: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['refresh']);

const deleteOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const token = localStorage.getItem('token');
    await axios.delete(`${import.meta.env.VITE_API_BASE}/order/${orderId}`, {
      
      headers: { Authorization: `Bearer ${token}` }
    });
    
    ElMessage.success('删除成功');
    emit('refresh');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败');
    }
  }
};

const handlePayment = async (order) => {
  try {
    order.paying = true;
    const token = localStorage.getItem('token');
    const response = await fetch(`${import.meta.env.VITE_API_BASE}/pay`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        orderId: order.order_id,
        orderTotalAmount: order.order_total_amount
      })
    });

    if (!response.ok) {
      throw new Error(await response.text());
    }

    const result = await response.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(result, 'text/html');
    const form = doc.querySelector('form');

    if (form) {
      document.body.innerHTML = '';
      document.body.appendChild(form);
      form.submit();
    } else {
      router.push({
        path: '/payment/success',
        query: {
          out_trade_no: order.order_id,
          total_amount: order.order_total_amount,
          timestamp: new Date().toISOString()
        }
      });
    }
  } catch (err) {
    ElMessage.error(`支付失败：${err.message || '未知错误'}`);
  } finally {
    order.paying = false;
  }
};
</script>

<style scoped>
.product-info {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.product-price {
  color: #e4393c;
  font-weight: bold;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status {
  padding: 5px 10px;
  border-radius: 3px;
  display: inline-block;
}

.delete-btn {
  margin-left: 10px;
}

.status.unpaid {
  background-color: #fff0f0;
  color: #e4393c;
}

.status.pending {
  background-color: #f0f9ff;
  color: #409eff;
}

.status.delivered {
  background-color: #f0fff0;
  color: #67c23a;
}
</style>